/*
 * Copyright (c) 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package google_io2011_logad;

import com.google.api.services.buzz.v1.Buzz;
import com.google.api.services.buzz.v1.model.Activity;
import com.google.api.services.buzz.v1.model.ActivityFeed;
import com.google.api.services.buzz.v1.model.ActivityObject;
import com.google.api.services.urlshortener.v1.Urlshortener;
import com.google.api.services.urlshortener.v1.model.Url;

import findreplace.RegexStringReplacer;

import java.io.IOException;

/**
 * Scan my Buzz posts for URLs and shorten them.
 *
 * @author aiuto@google.com (Tony Aiuto)
 */
public class UrlRewrite {

  // optimize transfer by only getting and setting some fields
  private static final String FIELDS_ACTIVITY = "object(content),object(originalContent)";

  /**
   * Scan my buzz posts for URLs and shorten them with UrlShortener.
   *
   * If in normal mode (expand=false):
   * 1. Get my Activity list.
   * 2. Scan the text for URLs that are not short already
   * 3. Build a short URL for each of these as we see them.
   * 4. If the text is changed, rewrite the Activity.
   *
   * If expand=true:
   * 1. Same as above except with the obvious reversals.
   */
  static void transformUrls(Buzz buzz, Urlshortener urlshortener,
                            boolean expand) throws IOException {
    Buzz.Activities.List request = buzz.activities.list("@me", "@self");
    request.maxResults = 10;
    ActivityFeed feed = request.execute();

    if (feed.items == null) return;  // No posts

    for (Activity activity : feed.items) {
      String oldContent = activity.buzzObject.originalContent;
      Log("-----------------------------------------------");
      Log("Original: " + oldContent);
      String newContent = scanAndProcess(urlshortener, oldContent, expand);
      Log("Content: " + newContent);

      if (!newContent.equals(oldContent)) {
        Activity replacement = new Activity();
        replacement.id = activity.id;
        replacement.buzzObject = new ActivityObject();
        replacement.buzzObject.content = newContent;
        replacement.buzzObject.originalContent = newContent;
        Buzz.Activities.Update updateRequest = buzz.activities.update(
            "@me", "@self", replacement.id, replacement);
        updateRequest.fields = FIELDS_ACTIVITY;
        Activity result = updateRequest.execute();
      }
    }
  }

  /** Look for URLs and shorten or expand them */
  static String scanAndProcess(Urlshortener urlshortener,
                               String text,
                               boolean expand) throws IOException {
    final String URL_REGEX =
        "(HTTPS?|https?)://[-._\\p{Alnum}/]*/[^ ()\\[\\]<>\"']*";
    RegexStringReplacer replacer = new RegexStringReplacer(text, URL_REGEX);
    while (replacer.next()) {
      String originalUrl = replacer.currentMatch();

      if (originalUrl.startsWith("http://bit.ly/")) continue;

      // Build and execute the request to shorten (or expand)
      String replacement = null;
      if (expand) {
        if (!originalUrl.startsWith("http://goo.gl/")) {
          Log("Skiping: " + originalUrl);
          continue;
        }
        try {
          Urlshortener.Url.Get request = urlshortener.url.get(originalUrl);
          Url response = request.execute();
          replacement = response.longUrl;
        } catch (IOException e) {
          Log("Could not expand the URL: " + originalUrl);
        }
      } else {
        if (originalUrl.startsWith("http://goo.gl/")) {
          Log("Skiping: " + originalUrl);
          continue;
        }
        try {
          Url requestBody = new Url();
          requestBody.longUrl = originalUrl;
          Urlshortener.Url.Insert request = urlshortener.url.insert(requestBody);
          Url response = request.execute();
          replacement = response.id;
        } catch (IOException e) {
          Log("Could not shorten the URL: " + originalUrl);
        }
      }
      if (replacement != null) {
        Log("Replaced <" + originalUrl + "> with <" + replacement + ">");
        replacer.replaceWith(replacement);
      }
    }
    return replacer.result();
  }

  private static void Log(String s) {
    System.out.println(s);
  }
}
